<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="handleSearchFunc"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFunc">查询</el-button>
      <el-button size="mini" @click="handleAdd"  v-functions="['workorder_setting_model_insert']">新增</el-button>
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
              ref="table"
              :headers="tableHeaders"
              :data="templateTableData"
              :pagingData="pagingData"
              @pageChange="handleCurrentChange"
              @pageSizeChange="handleSizeChange"
              @checkHeadersChange="checkHeadersChange">
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
                    :show-overflow-tooltip="true"
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop !== 'oprate' && item.prop !== 'status'">
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :width="68"
                    :key="index"
                    v-if="item.prop === 'status'">
              <template slot-scope="scope">
                <i class="V7_iconfont V7_iconV7tubiao_dian" :class="scope.row.status === 1 ? 'enable-span':'disable-span'"></i><span>{{scope.row.status === 1?'启用':'停用'}}</span>
              </template>
            </u-table-column>
            <u-table-column
                    :width="180"
                    :label="item.label"
                    :key="index"
                    v-if="item.prop === 'oprate' && item.show">
              <template slot-scope="scope">
                <span @click="handleDeploy(scope.row)" class="oprate-span" v-functions="['workorder_setting_model_edit']">配置</span>
                <span @click="handleEnableOrDisabled(scope.row)" class="oprate-span" :class="scope.row.status === 0 ?'':'red-span'" v-functions="['workorder_setting_model_enable']">{{scope.row.status === 1 ? '停用': '启用'}}</span>
                <span @click="handleDel(scope.row)" v-functions="['workorder_setting_model_delete']" class="oprate-span red-span">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import { commonAction } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import { TemplateModule } from '@/store/modules/config/template'
interface PageData {
  total: number
  limit: number
  page: number
}
@Component({
  name: 'customerTemplateSetting',
  components: {
    QuickSearch,
    configTable,
    continer
  }
})
export default class CustomerTemplateSetting extends Vue {
  // #region 基础数据
  [x: string]: any
  @Ref() private readonly table!: configTable
  private type: string = 'add' // 新增 || 编辑
  private quickSearchForm: any = {} // 快捷搜索表单 需动态变化
  private listLoading: boolean = false
  private templateTableData: any = [] // list 数据
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private checkHeaders: [] = [] // 当前展示的表头信息
  // #endregion

  // #region 高级搜索相关
  // 查询
  private handleSearchFunc () {
    this.pagingData.page = 1
    this.initData()
  }
  // #endregion

  // #region 数据表格相关
  // header 表头
  private tableHeaders: object[] = [ // 标头配置信息
    { label: '工单模型名称', prop: 'modelName' },
    { label: '创建时间', prop: 'createTime' },
    { label: '更新时间', prop: 'updateTime' },
    { label: '更新人', prop: 'updateUser' },
    { label: '状态', prop: 'status', sortable: true },
    { label: '操作', prop: 'oprate' }
  ]

  private handleEnableOrDisabled (row: any) { // 停用 / 启用
    this.$confirm(`确定要${row.status === 1 ? '停用' : '启用'}【${row.modelName}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const data = { url: '/server-work/action/workOrderModel/switch', method: 'post', data: { modelId: row.id, status: row.status ? 0 : 1 } }
      TemplateModule.TemplateCommonAction(data).then((res: any) => {
        if (res && res.success) {
          const str = row.status === 1 ? `停用【${row.modelName}成功】` : `启用【${row.modelName}】成功`
          this.$message({ message: str, type: 'success' })
          this.initData()
        }
      }).catch((e) => {
        console.log(e)
      })
    })
  }

  // operate 配置
  private handleDeploy (row: any) {
    this.$router.push({
      path: `/customer_template_setting/${row.id}/base`
    })
  }

  // operate 删除某行
  private handleDel (row: any) {
    this.$confirm('该操作将删除该模板及配置的所有信息，是否确认？', '确认删除模板', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.listLoading = true
      commonAction({
        url: `/server-work/action/workOrderModel/delete/${row.id}`,
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.$message.success('模板删除成功')
          this.initData()
        }
      }).finally(() => {
        this.listLoading = false
      })
    }).catch(e => {
      console.log(e)
    })
  }

  // 更改表头
  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  // 改变每页行数大小
  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  // 翻页
  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.initData()
  }
  // #endregion

  // #region 页面全局函数
  // 初始化列表
  private initData () {
    const actionData = Object.assign({ page: { pageNumber: this.pagingData.page, pageSize: this.pagingData.limit } }, this.quickSearchForm.form)
    this.listLoading = true
    TemplateModule.TemplateCommonAction({ url: '/server-work/action/workOrderModel/list', method: 'POST', data: actionData }).then(res => {
      if (res && res.success) {
        this.templateTableData = res.data.list || []
        this.templateTableData.forEach(item => {
          const agentObj = (CommonModule.publicCache.userListObj)[item.updateUser]
          item.updateUser = agentObj ? agentObj.name : '--'
        })
        this.pagingData.total = res.data.page.total || 0
        if (this.templateTableData.length === 0) {
          const page = Math.ceil(this.pagingData.total / this.pagingData.limit)
          if (!this.pagingData.total) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.queueTablePages.page = 1
          } else { // 删除到最后一个回到上一页
            this.queueTablePages.page = page
            this.initData()
            return false
          }
        }
      }
    }).finally(() => {
      this.listLoading = false
    })
  }

  // 新增模板
  private handleAdd () {
    this.$router.push({ path: '/customer_template_setting/addService/base' })
  }

  // #region 生命周期钩子
  private mounted () {
    this.quickSearchForm = { // 高级搜索数据
      form: {
        modelName: ''
      },
      advSearchOptions: [ // 高级搜索数据
        { label: '工单模型名称', name: 'modelName', inputType: 'input', clearable: true, placeholder: '请输入工单模型名称' }
      ]
    }
    this.handleSearchFunc()
  }
  // #endregion
}
</script>
<style lang="stylus" scoped>
  .oprate-span,.radio-span
    cursor pointer
    color $c-main
    margin 0 4px
  .red-span,.disable-span
    color $c-danger
  .enable-span
    color $c-green
  .disable-span,.enable-span
    font-size 12px
</style>
